var express = require('express');
var router = express.Router();
const cartSchema = require('../module/cart');
const shopsdetailSchema = require('../module/shopsdetail');
const jwt = require('jsonwebtoken');

let secret = 'houduan'
//添加到购物车，前端传参,id,token,num,color,size
router.post('/cartadd', function (req, res, next) {
    let { token, id, num } = req.body
    try {
        //把前端传进来商品信息的进行保存
        let data = jwt.verify(token, secret)
        let { username } = data
        let shop = {}
        shop.id = id
        shop.num = num
        //查看该用户是否有保存过
        cartSchema.findOne({ username }, (err, doc) => {
            if (err) throw err
            if (doc) {
                //有用户名，判断是否添加过该商品
                cartSchema.findOne({ username }, { shops: { $elemMatch: { id } } }, (err, doc) => {
                    if (err) throw err
                    console.log("doc", doc.shops)
                    if (doc.shops.length) {
                        //如果有商品则添加num                 
                        cartSchema.update({ username: username, 'shops.id': id }, { $inc: { 'shops.$.num': num } }, (err, doc) => {
                            if (err) throw err
                            res.json({
                                status: "0",
                                msg: "添加成功",
                            })
                        })
                    } else {
                        //把商品加到该用户下
                        cartSchema.updateOne({ username }, { $push: { shops: { id, num } } }, (err, doc) => {
                            if (err) throw err
                            res.json({
                                status: "0",
                                msg: "添加成功",

                            })
                        })
                    }
                })

            } else {
                //创建该商品
                cartSchema.create({ username, shops: shop })
                res.json({
                    status: "0",
                    msg: "添加成功",

                })
            }
        })
        cartSchema.update({ username }, { $push: { shops: shop } })
    } catch (error) {
        res.json({
            status: 4,
            msg: "token过期，请重新登入"
        })
    }

});


//获得购物车列表
router.post('/cartlist', function (req, res, next) {
    let { token } = req.body
    try {
        //把前端传进来商品信息的进行保存
        let data = jwt.verify(token, secret)
        let { username } = data
        let shopDetailList = []
        let shopInfo = []
        //根据token获得所有购物车数据
        async function getshopIdList() {
            //通过username在购物车列表找到用户
            await cartSchema.findOne({ username }, (err, doc) => {
                if (err) throw err
                shopDetailList = doc.shops

            })
            console.log("第一步", shopDetailList)
        }

        async function getinfodetail(shopid, shopnum) {
            let obj = {}
            await shopsdetailSchema.findOne({ "list.id": shopid }, (err, doc) => {
                let title = doc.title
                for (value of doc.list) {
                    if (value.id == shopid) {
                        obj.id = shopid;
                        obj.num = shopnum;
                        obj.url = value.url;
                        obj.detail = value.title;
                        obj.price = value.price;
                        obj.title = title
                        shopInfo.push(obj)
                    }
                }
            })
            console.log("第二步", shopInfo)
        }

        async function getinfolist() {
            //获得所有商品的idId
            await getshopIdList()
            console.log("shopDetailList===================", shopDetailList)
            //循环商品id在商品详情页获得商品详情
            for (value of shopDetailList) {
                let shopid = value.id
                let shopnum = value.num
                //获得需要的商品信息
                await getinfodetail(shopid, shopnum)
            }
            console.log("shopInfo===================", shopInfo)
            res.json({
                status: 0,
                msg: "获得成功",
                data: shopInfo
            })
        }
        getinfolist()
    } catch (error) {
        //判断token是否过期
        res.json({
            status: 4,
            msg: "token过期，请重新登入"
        })
    }
});


//修改购物车数量
router.post('/cartedit', function (req, res, next) {
    let { token, id, num } = req.body
    try {
        //获取token的标记
        let data = jwt.verify(token, secret)
        let { username } = data
        //数量修改
        cartSchema.update({ username, "shops.id": id }, { $set: { "shops.$.num": num } }, (err, doc) => {
            if (err) throw err
            res.json({
                status: "0",
                msg: "修改成功"
            })
        })

    } catch (error) {
        res.json({
            status: 4,
            msg: "token过期，请重新登入"
        })
    }

})


//删除购物车数据
router.post('/cartremove', function (req, res, next) {
    let { token, idlist } = req.body
    try {
        //获取token的标记
        let data = jwt.verify(token, secret)
        let { username } = data
        //数量修改
        for (value of idlist) {
            cartSchema.update({ username, "shops.id": value.id }, { $pull: { shops: { id: value.id } } }, (err, doc) => {
                if (err) throw err
                res.json({
                    status: "0",
                    msg: "删除成功"
                })
            })
        }


    } catch (error) {
        res.json({
            status: 4,
            msg: "token过期，请重新登入"
        })
    }

})


//获得购物车商品的数量
router.post('/cartnum', function (req, res, next) {
    let { token } = req.body
    try {
        //获取token的标记
        let data = jwt.verify(token, secret)
        let { username } = data
        //数量修改
        cartSchema.findOne({ username }, (err, doc) => {
            if (err) throw err
            res.json({
                status: "0",
                msg: "获取成功",
                data:doc.shops.length
            })
        })

    } catch (error) {
        res.json({
            status: 4,
            msg: "token过期，请重新登入"
        })
    }

})










module.exports = router;